package com.yx.shiroboot.config;

import com.sun.org.apache.bcel.internal.generic.RET;
import com.yx.shiroboot.realm.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * shiro配置类
 */
@Configuration
public class ShiroConfig {

    @Autowired
    MyRealm myRealm;

    //配置SecurityManager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(){
        //1、创建DefaultWebSecurityManager 对象
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //2、创建加密对象、设置相关属性
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
            //2.1采用MD5加密
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
            //2.2采用了迭代加密的次数
        hashedCredentialsMatcher.setHashIterations(3);
        //3、讲加密对象存储到myRealm中

        myRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        //4、讲myRealm存入 DefaultWebSecurityManager对象中
        defaultWebSecurityManager.setRealm(myRealm);
        //5、返回
        return defaultWebSecurityManager;
    }

    //配置shiro内置过滤器拦截范围
    @Bean
    public DefaultShiroFilterChainDefinition shiroFilterChainDefinition(){
        DefaultShiroFilterChainDefinition defaultShiroFilterChainDefinition = new DefaultShiroFilterChainDefinition();
        //设置不认证可以访问的资源
        defaultShiroFilterChainDefinition.addPathDefinition("/to/userLogin","anon");
        defaultShiroFilterChainDefinition.addPathDefinition("/to/login","anon");
        //设置需要进行登录认证的拦截范围
        defaultShiroFilterChainDefinition.addPathDefinition("/**","authc");
        return defaultShiroFilterChainDefinition;
    }

}
